var $navValueList = $("#navValueList");
var flag ;
var PATH_PREFIX ="";
var comboData =[];

function setPathPrefix(path){
	PATH_PREFIX =  path;
}

//初始化
$(function() {
	//给select2组件加载样式
	WASP_WIDGET.initializeSelectStyle();
	//产品
	//WASP_WIDGET.triggerPrdInfoSelect("q-fundSName",{multiple : true,selectType : 'prdName'});
	//项目经理
	//WASP_WIDGET.triggerSelectOnEmpId("#q-manager",{multiple : true});
	//部门
	//WASP_WIDGET.triggerSelectOnDeptId("q-department");
	//初始化日期
	WASP_WIDGET.triggerDateRangeStyle("q-navDate");
	// 注册清空事件
	WASP_WIDGET.registerResetClearEvent();
	//初始化多选框
	initMultipleSelectType();
	//默认加载查询列表
	expanderNavList();
});


//查询列表
function expanderNavList() {
	$navValueList.jqGrid({   
	url:PATH_PREFIX+'navInfoListPage.do',
	//caption:'招商财富产品净值列表<button type="button" class="btn btn-default btn-sm btn-small btn-fullscreen" title="" tabindex="-1"><i class="fa fa-arrows-alt icon-fullscreen"></i></button>',  
	datatype: "json",
	colNames:["","产品名称","产品代码","所属部门","项目经理","净值日期","净值","操作"],
	colModel:[  { name: 'navBizId', index: 'navBizId',hidden : true, key: true, width: 30, resizable: true, sortable: false }, 
		        { name: 'fundSname', index: 'fundSname', width: 30, resizable: true, sortable: false },       
	            { name: 'outCode', index: 'outCode', hidden : true,	width: 30, resizable: true, sortable: false },
	            { name: 'department', index: 'department',hidden : true , width: 30, resizable: true, sortable: false },
	            { name: 'projectManager', index: 'projectManager',hidden : true, width: 30, resizable: true, sortable: false },
	            { name: 'navDate', index: 'navDate', width: 30, resizable: true, sortable: false
	            	/*formatter:'date', formatoptions:{srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d'}*/ },
	            { name: 'nav', index: 'nav', width: 30, resizable: true, sortable: false },
	            { name: 'option', index: 'option', width: 30, resizable: true, sortable: false }
			  ],
	rowNum: 20,
    rowList: [20, 30, 50],
    rownumbers: true,
    rownumWidth: 50,
    prmNames: { search: "search", page: "pageNo", rows: "limit" },
    height: 'auto',
    width: false,
    autowidth:true,
    editurl: '',
    viewrecords: true,
    cellEdit: false,
    shrinkToFit: true,
    grouping: false,
    postData:{
    	'sp[prdCode]':$("#prdCode").val()
	},
    jsonReader: {
        root: "items", //结果集
        records: "total", //总记录数 
        total: "pageCount", //总页数
        page: "pageNo", //当前页 
        repeatitems: false // (4) 
    },  
	multiselect:true,
	pager: "#navValueListPage",					
	viewrecords: true,
	hidegrid: false, 
	gridComplete: function(){
		var ids = $navValueList.jqGrid('getDataIDs');
			for(var i=0;i < ids.length;i++){
				var id = ids[i];
				var rowData = $navValueList.jqGrid('getRowData', ids[i]);
				
			    var params = {
					'updateNav'	:	'updateNavTemp'
				};
				var permissionButton = Permission_Button.configPermissionButton(params);
				
				permissionButton.updateNav = Permission_Button.clickPermissionButton('updateNavTemp',"updateNavValues('" + id + "');");
				
				$navValueList.jqGrid('setRowData', ids[i], { option: Permission_Button.linkAllBtn(permissionButton)});
			}
	}
	});
	$navValueList.navGrid('#navValueListPage',{edit:false,add:false,del:false,search:false,refreshstate:'current'});
	$navValueList.jqGrid('setFrozenColumns');
	jqGridResize($navValueList);
}


function updateNavValues(id){
   var url = PATH_PREFIX+"updateNavDetail.do?navBizId="+id;
   openDialog(url);
}


function queryByCondtion(flag) {
	 var subPrdCode="";
	 var that = this;
     var arr = [];
     $.each($('.portCode-content i.fa-check-square'), function () {
     	arr.push($(this).data('val'));
     });
     subPrdCode = arr.join(',');
     if(arr.length==1){
    	 subPrdCode = arr[0] + ",";
     }
     
	var beginDate = $("#q-navDate").getDateRangeValue()[0];
	var endDate = $("#q-navDate").getDateRangeValue()[1];
	
	
	if (!flag) {
	
		var postData = $navValueList.jqGrid("getGridParam", "postData");
		$.extend(postData,{
			'sp[subPrdCode]':		subPrdCode,
			'sp[beginDate]':		beginDate,
			'sp[endDate]':			endDate,
			
		});
		$navValueList.trigger("reloadGrid", [{ page: 1 }]); 
	}else{
		produceCycle();
	}
}

//操作按钮 
var  NAV_SCOPE = {
		
		exportNavInfo : function(){
			
			 var subPrdCode="";
			 var that = this;
		     var arr = [];
		     $.each($('.portCode-content i.fa-check-square'), function () {
		     	arr.push($(this).data('val'));
		     });
		     subPrdCode = arr.join(',');
		     if(arr.length==1){
		    	 subPrdCode = arr[0] + ",";
		     }
			
			//日期
			var beginDate = $("#q-navDate").getDateRangeValue()[0];
			var endDate = $("#q-navDate").getDateRangeValue()[1];
			
			/*if (beginDate == '' || endDate == '') {
				ctools.alert_sweet("导出日期不能为空","warn","");
				return;
			} */
			var params  =  
		    	'&sp[subPrdCode]='	+			subPrdCode 				+
    			'&sp[beginDate]='	+			beginDate				+
    			'&sp[endDate]='		+			endDate;
			
			var url = PATH_PREFIX + "exportNavDetail.do?"+params;
			window.location = url ; 
		},
		exportNavExport: function() {
			window.open(PATH_PREFIX + "exportNavInterfaceFileView.do");
		}
}

//绘图
function produceCycle(){
	
	 	var lineChart = echarts.init(document.getElementById("style_full_line"));
	 	lineChart.clear();//刷新图表
	 	
	    var lineoption = {
	        title : {
	            text: '单位净值折线图'
	        },
	        tooltip : {
	            trigger: 'axis'
	        },
	        legend: {      
	            //left: 'right',  //控制图例显示方向
	            //left: 'center',  //控制图例显示方向
	            align: 'left', //水平方向位置
	            verticalAlign: 'top', //垂直方向位置
	            x: 150, //距离x轴的距离
	            y: 0 //距离Y轴的距离
	            //data: ['产品名称', '产品代码', '所属部门', '项目经理', '净值日期','单位净值'], //定义都有哪些图例显示
	            //selected:{
	            //    '产品名称':true,
	            //    '产品代码':true,
	            //    '所属部门':true,
	            //    '项目经理':true,
	            //   '净值日期':true,
	            //    '单位净值':true,
	            //}    //设置为false的代表初始化的时候隐藏，只有点击的时候折线才出来显示
	        },
	        //右上角工具条
//	        toolbox: {
//	            show : true,
//	            feature : {
//	                mark : {show: true},
//	                dataView : {show: true, readOnly: false},
//	                magicType : {show: true, type: ['line', 'bar']},
//	                restore : {show: true},
//	                saveAsImage : {show: true}
//	            }
//	        },
	        calculable : false,
	        xAxis : [
	            {
	                type : 'category',
	                name:'日期',
	                boundaryGap : false,
	                data :[]
	            }
	        ],
	        yAxis : [
	            {
	                type : 'value',
	                name:'净值'+'                  ',
	                axisLabel : {
	                    formatter: '{value}'
	                }
	            }
	        ],
	        series : []
	    };
	    lineChart.setOption(lineoption);
	    
	    var prdCode = $("#prdCode").val();
		var subPrdCode="";
		var that = this;
	    var arr = [];
	    $.each($('.portCode-content i.fa-check-square'), function () {
	     	arr.push($(this).data('val'));
	    });
	    subPrdCode = arr.join(',');
	    if(arr.length ==1){
	    	subPrdCode = arr[0] + ",";
	    }
		var beginDate = $("#q-navDate").getDateRangeValue()[0];
		var endDate = $("#q-navDate").getDateRangeValue()[1];
		
		var params  =  
	    	'&sp[subPrdCode]='	+			subPrdCode 				+
	    	'&sp[prdCode]='		+			prdCode 				+
			'&sp[beginDate]='	+			beginDate				+
			'&sp[endDate]='		+			endDate;
		
		var option = lineChart.getOption();     
		$.ajax({
			type : "POST",
			data: params,
			async : false, //同步执行  
			dataType : "json",
			url : PATH_PREFIX+'queryNavInfoBySolid.do',
			success : function(result) {
				
				//将从后台接收的json字符串转换成json对象
	            var jsonobj = eval(result);
	            
	            //给图标标题赋值
	            option.legend.data = JSON.parse(JSON.stringify(jsonobj.legend));
	            	console.log("图标标题:"+JSON.stringify(jsonobj.legend));
	            
	            //读取横坐标值
	            option.xAxis[0].data = jsonobj.category;
	            	console.log("横坐标值:"+jsonobj.category);
	            
	            var series_arr = jsonobj.series;
	            if(series_arr.length == 0){
	            	lineChart.clear();//没有数据，刷新图表
            		console.log("无数据");
            		ctools.alert_sweet("无数据","warn","");
	            	
	            }else{
	            	//驱动图表生成的数据内容，数组中每一项代表一个系列的特殊选项及数据
	            	for(var i = 0; i < series_arr.length; i++) {
	            		option.series[i] = result.series[i];
	            		console.log("数据:"+result.series[i].data);
	            	}
	            	//过渡控制，隐藏loading（读取中）
	            	lineChart.hideLoading();
	            	
	            	//为echarts对象加载数据
	            	lineChart.setOption(option);
	            }
			},
			error : function(jqXHR, textStatus, errorThrown) {
				console.log("生成折线后台日志:"+errorThrown);
				ctools.alert_sweet("查询数据出错","error","");
			}
		});
		
}


//列表页签
function showList(){
	$("#style_full_line").hide();;
	$("#style_full_list").show();
	$("#prdCode").show();
	$("#department").show();
	$("#manager").show();
	$("#queryBtn").show();
	$("#queryBtn2").hide();
	$navValueList.trigger("reloadGrid", [{ page: 1 }]);
	flag = false;
}

//折线页签
function showLine(){
	$("#style_full_line").show();
	$("#style_full_list").hide();
	$("#prdCode").hide();
	$("#department").hide();
	$("#manager").hide();
	$("#prdCode").val("");
	$("#department").val("");
	$("#manager").val("");
	$("#queryBtn").hide();
	$("#queryBtn2").show();
	var lineChart = echarts.init(document.getElementById("style_full_line"));
 	lineChart.clear();//刷新图表
	flag=true;
}

//回车键
$("body").keypress(function(event){
	var key = event.which;
	if(key == "13"){
		queryByCondtion(true);
	}
});


//初始化多选框
function initMultipleSelectType(){
	
	var pageApp = {
			  init: function () {
				  this.template = $('#_1').data('template');
				  this.url = $('#_1').data('url');
				  this.$resultBox = $('.result-box');
				  this.$loading = $('.loading');

				  this.getProduct();
				  this.bind();
				  this.initFilter();
			   }, 
			   bind: function () {
				   
				  this.$resultBox.on('click change', '#portCode', $.proxy(this.flitProductToComboList, this));
				  this.$resultBox.on('click', '.portCode-content li i', $.proxy(this.checkCombo, this));
				  this.$resultBox.on('click', '.portCode-content li span.check-all', $.proxy(this.checkCombo, this));
			      $(document).on('click', $.proxy(this.closeBox, this));
			      this.$resultBox.on('click', '.choose-box .choose i.fa-times', $.proxy(this.deleteChooseCombo, this));
			      this.$resultBox.on('click', '.choose-box .choose-clear', $.proxy(this.clearChooseCombo, this));
			      this.$resultBox.on('click', '.use-checkbox', $.proxy(this.checkboxChange, this));
			      /*this.$resultBox.on('click', '.table-search', $.proxy(this.refresh, this));*/
			      this.$resultBox.on('click', '#rtn', $.proxy(this.clearChooseCombo, this));
			    },
			    //勾选框点选
			    checkboxChange: function (e) {
			    	var $this = $(e.currentTarget);
			    	$this.toggleClass('fa-square').toggleClass('fa-check-square');
			    },
			    //清除所有已选组合
			    clearChooseCombo: function () {
			    	$('.choose i.fa-times').click();
			    },
			    //删除已选组合
			    deleteChooseCombo: function (e) {
			    	var $this = $(e.currentTarget);
			    	var val = $this.data('val');
			    	$this.parent().remove();
			    	$('.portCode-content i.fa-check-square[data-val="' + val + '"]').removeClass('fa-check-square').addClass('fa-square');
			    },
			    //点击页面空白关闭下拉
			    closeBox: function (e) {
			    	var $this = $(e.target);
			    	if ($this.parents('.portCode-content').length > 0) {
			    		return
			    	}
			    	$('.portCode-content').hide();
			    },
			  //初始化查询条件
			    initFilter: function(){
			      if($("#department").length == 1){
			    	  var arr = ['<option value="DEP000">全部部门</option>'];
			    	  var dep = [{name:'全部产品', value:'ZSCF000000'}];
			  		  for(var i in this.comboData){
				  			if(i == "DEP000"){
				  				arr.push('<option value="DEP000">全部部门</option>');
				  			}else{
				  				arr.push('<option value="' + i + '">' + i + '</option>');
				  			}
				  			dep = dep.concat(this.comboData[i]);
				  			this.comboData[i] = [{name:'全部产品', value:'ZSCF000000'}].concat(this.comboData[i]);
			  		  }
			  		  this.comboData['DEP000'] = dep;
			  		  $('#department').html(arr.join());
			  		  $('#department').select2({width: '140px'});;
			      }
			      $('#portCode').click();
			      $('#portCode').parent().click();
			      if($(".input-date").length > 0){
			    	  this.initDatePlug();
			      }
			        
			      if($("#endDate").length > 0){
			    	  $("#endDate").datepicker('setDate', this.getNowDate(1));
			      }
			        
			      if($("#begDate").length > 0){
			    	  $("#begDate").datepicker('setDate', this.getNowDate(31));
			      }
			        
			      if($("#isPassFuture").length > 0){
//			      	this.initParam();
			      }
			    },
			  //点击勾选组合
			    checkCombo: function (e) {
			    	e.stopPropagation();
			    	var $this = $(e.currentTarget);
			    	if ($this.hasClass('check-all')) {
			    		$this.parents('ul').find('i.fa-square').click();
			    		return
			    	}
			    	if ($this.hasClass('fa-square')) {
			    		var chooseClear = '<div class="choose-clear">删除全部已选</div>';
			    		var choose = '<div class="choose" data-val="' + $this.data('val') + '">' + $this.data('name') + '<i class="fas fa-times" data-val="' + $this.data('val') + '"></i></div>';
			    		if ($this.data('val') == 'ZSCF000000') {
			    			$('.portCode-content i.fa-check-square').removeClass('fa-check-square').addClass('fa-square');
			    			$this.removeClass('fa-square').addClass('fa-check-square');
			    			$('.choose').remove();
			    		}else {
			    			if ($($('.choose')[0]).data('val') == 'ZSCF000000') {
			    				$('.choose').remove();
			    				if ($($('.portCode-content i.fa-check-square')[0]).data('subFundSname') == '全部产品') {
			    					$('.portCode-content i.fa-check-square')[0].click();
			    				}
			    			}
			    			$this.removeClass('fa-square').addClass('fa-check-square');
			    		}
			    		$('.choose-box .choose-clear').remove();
			    		$('.choose-box').append(choose).append(chooseClear);
			    	}else {
			    		$this.removeClass('fa-check-square').addClass('fa-square');
			    		$('.choose[data-val="' + $this.data('val') + '"]').remove();
			    	}
			    },
			    //获取产品信息
			    getProduct: function (){
			    	var WIDGET_PATH_PREFIX = ctx + "system/widget/";
			    	var that = this;
			    	//this.$loading.show();
			    	$("#loading").show();
			    	var subFundSname = $("#portCode").val();
			    	var params  = { 
			    			'prdcode':null,//添加参数，方便传参实现联动
					    	'subFundSname':subFundSname,
					};
			    	$.ajax({
			    		  type: "POST",
			    		  url: WIDGET_PATH_PREFIX + "queryMatchSubPrdInfoList.do",
			    		  data: params,
			    		  async: false,
			    		  dataType: "json",
			    		  success: function (data) {
			    		  	that.comboData = data;
			    		  },
			    		  complete: function () {
			    		  	//that.$loading.hide();
			    		  	$("#loading").hide();
			    		  }
			    	});
			    	
			    },
			    //点击部门筛选对应的产品添加到组合列表中
			    flitProductToComboList: function (e) {
			    	
			    	pageApp.getProduct();
			    	e.stopPropagation();
			    	var $this = $(e.currentTarget);
			    	var val = $this.val();
			    	
			    	var data = this.comboData;
			    	var d = {};
			    	if (val == '') {
			  			d.result = data;
			  			var $tpl = $('#option_template1').html();
			    	}else {
			    		var arr = [];
			    		$.each(data, function () {
			    			if (this.subFundSname.indexOf(val) > -1) {
			    				arr.push(this);
			    			}
			    		});
			    		d.result = arr;
			    		if (arr.length == 0) {
			    			var $tpl = $('#option_template1').html();
			    		}else {
			    			var $tpl = $('#option_template2').html();    			
			    		}
			    	}
			    	var html = Mustache.render($tpl, d);
						$('.portCode-content ul').html(html);
						$('.portCode-content').show();
						if ($('.choose').length == 0 && $($('.portCode-content i.fa-square')[0]).data('subFundSname') == '全部产品') {
							$('.portCode-content i.fa-square')[0].click();	
						}else {
							$.each($('.choose'), function () {
								$('.portCode-content i[data-val="' + $(this).data('val') + '"]').addClass('fa-check-square').removeClass('fa-square');
							});
						}
			    }
	 		};
			//$("#portCode").on('click',$.proxy(pageApp.getDepartmentProduct, pageApp));
	 		pageApp.init();
	 		
	 		
}

